package com.elinkway.infinitemovies.adapter;

import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;


public abstract class BaseRecyclerListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
  protected List<Object> mItemList = new ArrayList<>();

  public BaseRecyclerListAdapter() {
  }

  public BaseRecyclerListAdapter(@NonNull Object[] arrays) {
    if (arrays == null) {
      throw new IllegalArgumentException("don't pass null in");
    }
    mItemList.addAll(Arrays.asList(arrays));
  }

  public BaseRecyclerListAdapter(@NonNull Collection<Object> collection) {
    if (collection == null) {
      throw new IllegalArgumentException("don't pass null in");
    }
    mItemList.addAll(collection);
  }

  public BaseRecyclerListAdapter(@NonNull List<Object> list) {
    if (list == null) {
      throw new IllegalArgumentException("don't pass null in");
    }
    mItemList = list;
  }

  @Override
  public int getItemCount() {
    return mItemList == null ? 0 : mItemList.size();
  }

  public List<Object> getItemList() {
    return mItemList;
  }

  @UiThread
  public void setItemList(List<Object> itemList) {
    mItemList.clear();
    mItemList = itemList;

    notifyDataSetChanged();
  }

  public Object getItem(int position) {
    if(mItemList != null && mItemList.size() > position) {
      return mItemList.get(position);
    } else {
      return null;
    }
  }

  @UiThread
  public BaseRecyclerListAdapter add(@NonNull Object item) {
    mItemList.add(item);
    notifyItemInserted(mItemList.size() - 1);
    return this;
  }

  @UiThread
  public BaseRecyclerListAdapter addAll(@NonNull Object[] items) {
    return addAll(Arrays.asList(items));
  }

  @UiThread
  public BaseRecyclerListAdapter addAll(@NonNull Collection<Object> items) {
    mItemList.addAll(items);
    notifyItemRangeInserted(mItemList.size() - items.size(), items.size());
    return this;
  }

  @UiThread
  public BaseRecyclerListAdapter add(int position, @NonNull Object item) {
    mItemList.add(position, item);
    notifyItemInserted(position);
    return this;
  }

  @UiThread
  public BaseRecyclerListAdapter remove(int position) {
    mItemList.remove(position);
    notifyItemRemoved(position);
    return this;
  }

  @UiThread
  public BaseRecyclerListAdapter remove(@NonNull Object item) {
    return remove(mItemList.indexOf(item));
  }

  @UiThread
  public BaseRecyclerListAdapter clear() {
    mItemList.clear();
    notifyDataSetChanged();
    return this;
  }

  public boolean isEmpty() {
    return mItemList == null || mItemList.isEmpty();
  }

}